import java.util.Arrays;

public class Heap {
    public int[] array;
    public int size;
    public Heap(){
        this.array=new int[10];
    }
    public void createArray(int[] arr){
        for (int i = 0; i <arr.length ; i++) {
            array[i]=arr[i];
            size++;
        }
    }
    public void createHeap(int[] array){
        for (int parent =(size-1-1)/2; parent >=0 ; parent--) {
            down(parent,size);
        }
    }
    //向下调整
    private void down(int parent, int size) {
        int child=2*parent+1;
        while (child<size){
            if (child+1<size&&array[child]<array[child+1]){
                child++;
            }
            if (array[child]>array[parent]){
               swap(child,parent);
                parent=child;
                child=2*parent+1;
            }else {
                break;
            }
        }
    }
    public void swap(int i,int j){
        int temp=array[i];
        array[i]=array[j];
        array[j]=temp;
    }
    //插入元素
    public void offer(int val){
        if(isFull()){
            array= Arrays.copyOf(array,2*array.length);
        }
        array[size]=val;
        up(size);
        size++;
    }
    //向上调整
    public void up(int child){
        int parent=(child-1)/2;
        while (parent>=0){
            if (array[child]>array[parent]){
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else {
                break;
            }
        }

    }
    public  boolean isFull(){
        return size==array.length;
    }
    //删除
    public int poll(){
        if (isEmpty()){
            return -1;
        }
        int val=array[0];
        swap(0,size-1);
        down(0,size);
        return val;

    }
    public boolean isEmpty(){
        return size==0;
    }
    public int peek(){
        if (isEmpty()){
            return -1;
        }
        return array[0];
    }
}
